package cn.jwcat.service.impl;

import cn.jwcat.entity.Area;
import cn.jwcat.entity.Room;
import cn.jwcat.mapper.AreaMapper;
import cn.jwcat.service.IAreaService;
import cn.jwcat.service.IRoomService;
import cn.jwcat.utils.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 房区 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-04-13
 */
@Transactional
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {

	@Resource
	IRoomService roomService;

	@Override
	public Result changeState(Area area) {
		// 判断该房区是否还有启用的房间
		LambdaQueryWrapper<Room> roomLambdaQueryWrapper = new LambdaQueryWrapper<>();
		roomLambdaQueryWrapper
			.eq(Room::getStatus, true)
			.eq(Room::getAreaId, area.getAreaId());
		List<Room> rooms = roomService.getBaseMapper().selectList(roomLambdaQueryWrapper);
		System.out.println(rooms.toString());
		if (rooms.size() != 0) return Result.error().message(area.getAreaName() + "区有房间正处于开启状态，请重新检查");
		if (area.getStatus()) {
			area.setUpdateTime(LocalDateTime.now());
		}
		// 修改房区状态
		LambdaUpdateWrapper<Area> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper
			.set(Area::getStatus, area.getStatus())
			.set(Area::getUpdateTime, area.getUpdateTime())
			.eq(Area::getAreaId, area.getAreaId());
		boolean bool = this.update(updateWrapper);
		if (bool) return Result.code(200).message(area.getAreaName() + " 区状态修改成功！");
		return Result.code(401).message(area.getAreaName() + " 区状态修改失败！请再次操作！");
	}
}
